﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Form1
{
    public class DataManager
    {
        public static DataManager Instance { get; } = new DataManager();

        public TestDataRoot DataRoot { get; protected set; }

        private string _jsonPath = Path.Combine(_baseDir,"./app.json");

        private const string _baseDir = "./Data";

        private DataManager()
        {
            if (!Directory.Exists(_baseDir))
            {
                Directory.CreateDirectory(_baseDir);
            }

            if (File.Exists(_jsonPath))
            {
                using (StreamReader reader = new StreamReader(new FileStream(_jsonPath, FileMode.Open)))
                {
                    DataRoot = JsonConvert.DeserializeObject<TestDataRoot>(reader.ReadToEnd());
                }
            }
            else
            {
                DataRoot = new TestDataRoot();
                DataRoot.DataSet = new List<string>();
            }
        }

        public void SaveDataRoot()
        {
            using (StreamWriter writer = new StreamWriter(new FileStream(_jsonPath, FileMode.Create)))
            {
                writer.Write(JsonConvert.SerializeObject(DataRoot));
            }
        }

        public void SaveData(TestData testData)
        {
            string fileName = GenerateDataFileName(testData);
            if (!DataRoot.DataSet.Contains(fileName))
            {
                DataRoot.DataSet.Add(fileName);
                SaveDataRoot();
            }

            using (StreamWriter writer = new StreamWriter(new FileStream(fileName, FileMode.Create)))
            {
                writer.Write(JsonConvert.SerializeObject(testData));
            }
        }

        public bool Delete(string fileName)
        {
            try
            {
                DataRoot.DataSet.Remove(fileName);
                SaveDataRoot();
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }
                return true;
            }
            catch(Exception ex)
            {
                return false;
            }
        }

        private string GenerateDataFileName(TestData testData)
        {
            return Path.Combine(_baseDir,testData.StartDate.ToString("yyyy-MM-dd HH.mm.ss") + testData.LineIndex+".json");
        }

        public TestData GetTestDataByFileName(string fileName)
        {
            try
            {
                using (StreamReader reader = new StreamReader(new FileStream(fileName, FileMode.Open)))
                {
                    return JsonConvert.DeserializeObject<TestData>(reader.ReadToEnd());
                }
            }
            catch
            {
                return null;
            }
        }
    }
}
